<?php
namespace Components\Account\User;

class Logic {
	private function getPaginate($builder, $limit, $page) {
		return ['code' => 0, 'pager'=>(new \Phalcon\Paginator\Adapter\QueryBuilder([
			'builder' => $builder,
			'limit' => $limit,
			'page' => $page
		])) -> getPaginate()];
	}

	private function makeBuilder($parameters) {
		$builder = (new \Phalcon\Mvc\Model\Query\Builder())
			-> from([
				'u' => __NAMESPACE__ . '\\Model'
			])
			-> columns(
				'u.user_id,u.pid,u.cellphone,u.account,u.level,u.create_time,u.status'
			)
			-> orderBy('u.status DESC, u.user_id DESC');

		if(isset($parameters['conditions']) && !empty($parameters['conditions'])) {
			$builder -> where($parameters['conditions']);
		}
		return $builder;
	}

	public function pager($parameters = [], $limit = 10, $page = 1) {
		$pager = $this -> getPaginate($this -> makeBuilder($parameters), $limit, $page);
		$tPager = $pager['pager'] -> items -> toArray();
		foreach($tPager as $k => $v) {
			if($v['pid'] == 0) {
				$tPager[$k]['p_account'] = '无';
			} else {
				$pUser = Model::findFirst('user_id = ' . $v['pid']);
				if(!$pUser) {
					$tPager[$k]['p_account'] = '无';
				} else {
					$tPager[$k]['p_account'] = $pUser -> account;
				}
			}

			$findFirstWallet = Wallet\Model::findFirst('user_id = ' . $v['user_id']);
			if($findFirstWallet) {
				$tPager[$k]['price_retail'] = $findFirstWallet -> price_retail;
				$tPager[$k]['price_business'] = $findFirstWallet -> price_business;
				$tPager[$k]['price_shop'] = $findFirstWallet -> price_shop;
				$tPager[$k]['price_trade'] = $findFirstWallet -> price_trade;
				$tPager[$k]['price_activation'] = $findFirstWallet -> price_activation;
			} else {
				$tPager[$k]['price_retail'] = 0;
				$tPager[$k]['price_business'] = 0;
				$tPager[$k]['price_shop'] = 0;
				$tPager[$k]['price_trade'] = 0;
				$tPager[$k]['price_activation'] = 0;
			}
		}
		$pager['pager'] -> items = $tPager;
		return $pager;
	}
}
